package vue;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import metier.DefaultHttpClientPerso;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.finalprojet.R;

public class Reglage extends Activity {
	
	 String[] Reglage = {"Ajouter un ami","Enlever un ami","Changer photo de profil"};
	 public Dialog dialog;
	 String pseudo;
	 public String id;
	 public Bitmap bmp;


	 
	 @Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
         if ((keyCode == KeyEvent.KEYCODE_BACK)) {
         	Intent nextScreen = new  Intent (getApplicationContext(), DashBoard.class );
         	nextScreen.putExtra("pseudo", pseudo);
				startActivity (nextScreen);
         }
         return super.onKeyDown(keyCode, event);
     }
	 
	 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reglage);
        
        pseudo = getIntent().getStringExtra("pseudo");
        id = getIntent().getStringExtra("id");
       
        
       
        
        
       
        ListView Listregl = (ListView)findViewById(R.id.listreglage);
        Listregl.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Reglage));
        
        
        
        Listregl.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				
				//int layout=0;
				//if ( arg2 == 1 ) layout = R.layout.addamis ;
				//if ( arg2 == 1 ) layout = R.layout.addamis ;
				//if ( arg2 == 1 ) layout = R.layout.addamis ;
				
				//buildAlertdialog(Reglage[arg2],layout);
				
				if ( arg2 == 0 ) buildAlertdialog(Reglage[arg2],R.layout.addamis );
				
				
				if ( arg2 == 1 ) 
					{ 
					
					Intent nextScreen = new  Intent (getApplicationContext (), SuprAmis.class );
        			nextScreen.putExtra("pseudo", pseudo);
        			nextScreen.putExtra("id", id);
    				startActivity (nextScreen);
					
					}
				
				if ( arg2 == 2 ) 
				{ 
				
				Intent nextScreen = new  Intent (getApplicationContext (), UploadImage.class );
				nextScreen.putExtra("id", id);
				startActivity (nextScreen);
				
				}

 
				
			}
		});

	 
        
        
        
        
        
        
        
        
        
    } 
    
    
    void buildAlertdialog(String titre,int layout)
    {
    	dialog = new Dialog(Reglage.this);
 		dialog.setTitle(titre);
 		
 		 dialog.setContentView(layout);
 		
 		dialog.setCancelable(true);
 		


 			final EditText amis = (EditText)dialog.findViewById(R.id.amis);
 			Button ajouter = (Button)dialog.findViewById(R.id.ajouter);
 			

 			
 			
 			 
 			 
 			ajouter.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					
					PreAjouterAmis AjouterAmis = new PreAjouterAmis();
					AjouterAmis.execute(amis.getText().toString(),pseudo);
					}
			});
 			dialog.show();
 			
 			
 		}
    
    
    
    
    
    public class PreAjouterAmis extends AsyncTask< String, Void, String>  {
    	
    	private String amis;
    	
    	
    	
    	
    	protected String doInBackground(String... arg0) {
    		
    		Log.e("add","ok");
    		DefaultHttpClientPerso httpclient = new DefaultHttpClientPerso();
    	
 
    		amis = arg0[0];
    		pseudo =  arg0[1];
    		
    		HttpPost httpget = new HttpPost("https://spartacus.iutc3.unicaen.fr/~projet.echec/android/verifieramis.php?amis="+amis+"&pseudo="+pseudo);
    		
    		HttpResponse response = null;
    		String responseString = null;
    		
    		
    		 try {
    		
    			 response = httpclient.execute(httpget);
    			
    		 } catch (ClientProtocolException e) {
    		       e.printStackTrace();
    		    } catch (IOException e) {
    		    	 e.printStackTrace();
    		    } 
    		    
    		    HttpEntity entity = response.getEntity();
    		 
    		 if ( entity != null )
    			 try {
    				 responseString = EntityUtils.toString(entity);
    			 } catch (ParseException e) {
    					e.printStackTrace();
    			    } catch (IOException e) {
    			    	e.printStackTrace();
    			    }
    		
    
    		 String url = EcranAccueil.URLSERVEUR+"android/upload/smallimg/";
    		 
    		
    		 String id = null;
        			//JSONArray array = new JSONArray(result);
        			Log.e("rep",responseString);
        			JSONObject main;
					try {
						main = new JSONObject(responseString);
						id = main.get("id").toString();
					} catch (JSONException e1) {
						e1.printStackTrace();
					}
        			
        			
    			
    		 
    		 
             url+=id+".jpg";
             Log.e("url",url);
            
 	      	try {
 	      	 final URLConnection conn = new URL(url).openConnection();
 	      	 
 	      	 String userpassword = "projet.echec" + ":" + "eepuhohx";
   	      String encodedAuthorization =  Base64.encodeToString( userpassword.getBytes(), Base64.NO_WRAP );
   	      conn.setRequestProperty("Authorization", "Basic "+
   	            encodedAuthorization);
   	      
				conn.connect();
			
 	      	
 	      	final InputStream is = conn.getInputStream();
 	       
 	      	final BufferedInputStream bis = new BufferedInputStream(is, 100000);
 	       
 	      	final Bitmap bm = BitmapFactory.decodeStream(bis);
 	      	bis.close();
 	      	is.close();
 	      	
 	      	

 	      	bm.getScaledHeight(40);
 	      	bm.getScaledWidth(40);
				bmp = bm;
				
 	      	} catch (IOException e) {
				e.printStackTrace();
			}
    		 
    		 return responseString;
    		
    			 	}

    	
    	@Override
    	protected void onPostExecute(String result) {
    //		String toast = null;
    		//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
    		try {
    			
    			//JSONArray array = new JSONArray(result);
    			
    			JSONObject main =new JSONObject(result);
    			String erreur = main.get("amis").toString();
    			
    			//Toast.makeText(getApplicationContext(),erreur,Toast.LENGTH_SHORT).show();	
    			if ( erreur.isEmpty() || erreur.equals("dejaamis") || erreur.equals(pseudo) )
    				
    			{
    				
    				if ( erreur.isEmpty() ) Toast.makeText(getApplicationContext(),"Le pseudonyme n'existe pas",Toast.LENGTH_SHORT).show();	
    				if ( erreur.equals("dejaamis") ) Toast.makeText(getApplicationContext(),"D�ja amis avec cette personne",Toast.LENGTH_SHORT).show();
    				if ( erreur.equals(pseudo) ) Toast.makeText(getApplicationContext(),"C'est Vous",Toast.LENGTH_SHORT).show();
    					
    				
    				
    				
    			}
    			
    			
    			
    				
    			

    			else 
    				{
    				
    				//toast = "Vous vener d'ajouter : " + main.get("amis").toString();
    				//Toast.makeText(getApplicationContext(),toast,Toast.LENGTH_SHORT).show();
    				//Intent nextScreen = new  Intent (getApplicationContext(), MainActivity.class );
    				dialog.cancel();
    				
    				// ImageView img = (ImageView) findViewById(R.id.ImageView01);
    				 //Log.e("img",img.toString());
    				 //Log.e("bmp",bmp.toString());
    				
    				
    				 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Reglage.this);
    					alertDialogBuilder.setTitle(main.get("amis").toString());
    					ImageView img = new ImageView(Reglage.this);
        				img.setImageBitmap(bmp);
    					
    					alertDialogBuilder.setView(img)
    						.setMessage("Voulez vous ajouter "+main.get("amis").toString()+" a votre liste d'amis ")
    						.setCancelable(false)
    						.setPositiveButton("Ajouter",new DialogInterface.OnClickListener() {
    							public void onClick(DialogInterface dialog,int id) {
    								AjouterAmis AjouterAmis = new AjouterAmis();
    								AjouterAmis.execute(amis,pseudo);
    								Intent nextScreen = new  Intent (getApplicationContext(), DashBoard.class );
    		        				nextScreen.putExtra("pseudo", pseudo);
    		        				startActivity (nextScreen);
    							}
    						  });
    					alertDialogBuilder
    					.setNegativeButton("Ne pas ajouter",new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int id) {
								dialog.cancel();
							}
						  });

    						AlertDialog alertDialog = alertDialogBuilder.create();
    						alertDialog.show();
 
    				
    				
    				
    				
    				
    				
    					
    				

    				}
    			
    			

    			
    		} catch (Exception e) {
    			Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
    		}
    		
    		
    		

    		
    			
    	}

    }


    
    
    
    
    
 public class AjouterAmis extends AsyncTask< String, Void, String>  {
    	
    	
    	
    	
    	protected String doInBackground(String... arg0) {
    		

    		DefaultHttpClientPerso httpclient = new DefaultHttpClientPerso();
    	
    		HttpGet httpget = new HttpGet("http://spartacus.iutc3.unicaen.fr/~projet.echec/android/ajouteramis.php?amis="+arg0[0]+"&pseudo="+arg0[1]);
    	//HttpPost httpget = new HttpPost("http://10.0.2.2//android/ajouteramis.php");
/*
    		List<NameValuePair> arg = new ArrayList<NameValuePair>(1);
    		arg.add(new BasicNameValuePair("amis", arg0[0] ));
    		arg.add(new BasicNameValuePair("pseudo", arg0[1] ));

    		  try {
    	          httpget.setEntity(new UrlEncodedFormEntity(arg));
    	      } catch (UnsupportedEncodingException e) {
    	          
    	          e.printStackTrace();
    	      }*/

    		HttpResponse response = null;
    		String responseString = null;
    		
    		
    		 try {
    		
    			 response = httpclient.execute(httpget);

    		 } catch (ClientProtocolException e) {
    			 e.printStackTrace();
    			 } catch (IOException e) {
    				 e.printStackTrace();    		    } 
    		    
    		    HttpEntity entity = response.getEntity();
    		 
    		 if ( entity != null )
    			 try {
    				 responseString = EntityUtils.toString(entity);
    			 } catch (ParseException e) {
    					e.printStackTrace();
    			    } catch (IOException e) {
    			    	e.printStackTrace();
    			    }
    		
    		
 	      	
    		 

    		 return responseString;
    		
    			 	}

    	
    	@Override
    	protected void onPostExecute(String result) {
    		
    		
      		//Toast.makeText(getApplicationContext(),result , Toast.LENGTH_LONG).show();  

    		String toast = null;
    		String amis = null;
    		
    			
    		JSONObject main = null;
    			
    			try {
    				main = new JSONObject(result);
					amis = main.get("amis").toString();
				} catch (JSONException e) {
					e.printStackTrace();
				}

    			
    			
    			
    				
    			

    				toast = "Vous vener d'ajouter : " + amis;
    				Toast.makeText(getApplicationContext(),toast , Toast.LENGTH_LONG).show();  
    				dialog.cancel();
    				
    				
    		

    		
    			
    	}

    }
 
 
 
 
 

    }
    
    

    
    
        
        
       

